import React from 'react'

import { connect } from 'react-redux'
import { addAction, subAction } from '../store/actions';

class Item extends React.Component {
  render() {
    console.log('item:', this.props)
    const { pname, num, add, sub } = this.props;
    return (
      <div>
        <button onClick={() => {
          add()
        }}>+</button>
        <button onClick={() => {
          sub()
        }}>-</button>
        <span>【{pname}】商品的数量【{num}】</span>
      </div>
    )
  }
}

// 连接store获取数据
const mapStateToProps = (state, ownProps) => {
  console.log('获取state数据：',state, ownProps)
  return {
    num: state[ownProps.pname]
  }
}

// 连接到store获取操作state数据的方法
const mapDispatchToProps = (dispatch, ownProps) => {
  console.log('获取操作state方法：',dispatch, ownProps)
  const { pname } = ownProps;
  return {
    // 购物车商品数量加一
    add() {
      dispatch(addAction(pname))
    },
    // 购物车商品数量减一
    sub() {
      dispatch(subAction(pname))
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Item)
